package com.google.code.expr.runtime;

import java.text.ParseException;

public class EXPRValue {
	private Object value;
	
	public EXPRValue(Object pVal) {
		super();
		setValue(pVal);
	}
	
	public Object getValue() {
		return value;
	}
	private void setValue(Object pVal) {
		this.value = pVal;
	}
	public void setVariable(EXPRVariable pOther) {
		setValue(pOther.getValue());
	}
	public void setString(String pValue) {
		setValue(pValue);
	}
	public void setBoolean(Boolean pValue) {
		setValue(pValue);
	}
	public void setNumber(Number pValue) {
		setValue(pValue);
	}
	
	public boolean isString() {
		return value!=null && value instanceof String;
	}
	public boolean isBoolean() {
		return value!=null && value instanceof Boolean;
	}
	public boolean isNumber() {
		return value!=null && value instanceof Number;
	}
	
	public String getString() {
		return value!=null && value instanceof String ? (String)value : null;
	}
	public Boolean getBoolean() {
		return value!=null && value instanceof Boolean ? (Boolean)value : null;
	}
	public Number getNumber() {
		return value!=null && value instanceof Number ? (Number)value : null;
	}
	
	public String resolveAsString() {
		if (value!=null) {
			if (isBoolean()) {
				return EXPRValueConverter.serializeBoolean(getBoolean());
			}
			else if (isNumber()) {
				return EXPRValueConverter.serializeNumber(getNumber());
			}
			else {
				return getString();
			}
		}
		else {
			return null;
		}
	}

	public Number resolveAsNumber() {
		if (value!=null) {
			if (isBoolean()) {
				return null;
			}
			else if (isNumber()) {
				return getNumber();
			}
			else {
				try {
					return EXPRValueConverter.parseNumber(getString());
				} 
				catch (ParseException e) {
					return null;
				}
			}
		}
		else {
			return null;
		}
	}
	
	public String toString() {
		if (isString()) {
			return '"' + resolveAsString() + '"';
		}
		else {
			return resolveAsString();
		}
	}
}
